import { checkApplePayResult,advanceOrder } from '@/api/api'
import { userData } from "@/store/userData";
import { userData } from "@/store/userData";
import {showLoading,closeLoading} from '@/utils/utils'
import { systemConfig } from "@/store/systemConfig";

const wait = (time:number)=>{
    return new Promise((resolve, reject)=>{
        if(!time){
            resolve(true)
        }else{
            setTimeout(()=>{
                resolve(true)
            },time)
        }
    })
}



let _iap = null

let _productDetail = null

let _advanceOrderProId = null

let _productIds = ['ssq001']


let _slimType = 1;

let _totalAmount = null;

let _merOrderId = null

let _payResult = null


const _init = ({appleProductId,totalAmt,productId}:any)=>{
    _iap = null;
    _productDetail = null;
    _productIds = [appleProductId];
    _payResult = null;
    _totalAmount = totalAmt;
    _advanceOrderProId = productId;
    _merOrderId = null;
}


const AdvanceOrder = async()=>{

    const USER_DATA = userData();

    const params = {
        userId:USER_DATA.id,
        slimType:Number(_slimType),
        totalAmt:Number(_totalAmount),
        productId:_advanceOrderProId,
    }

    const res:any = await advanceOrder(params);
    const {flag,message} = res;
    if(flag!==1){
        uni.showToast({
            icon: "none",
            title: message,
            duration: 3000,
        });
        closeLoading();
        return Promise.reject(message)
    }

    console.log('AdvanceOrder success')

    console.log(res);

    _merOrderId = res.data.merOrderId;
}


export const getProvider = () => {
  return new Promise((resolve, reject) => {
    uni.getProvider({
      service: "payment",
      success(res){
        console.log(res);
		console.log(res.providers)
        _iap = res.providers.find((channel) => {
            return (channel.id === 'appleiap')
          })
          if(!_iap){
             uni.showToast({
                icon: "none",
                title: "渠道不存在",
                duration: 1500,
              });
              closeLoading();

              reject(false)

          }
        resolve(true);
      },
      fail(err){
        reject(err);
      }
    });
  });
};

export const requestProduct = ()=>{
    if(!_iap){
        return
    }

    return new Promise((resolve, reject) => {
        let unfinishAppleOrder1 = uni.getStorageSync("unfinishAppleOrder1");
            if(unfinishAppleOrder1){
                unfinishAppleOrder1 = JSON.parse(unfinishAppleOrder1)
            }else{
                unfinishAppleOrder1 = [];
            }
            unfinishAppleOrder1.push(_productIds[0]);

            uni.setStorageSync('unfinishAppleOrder1',JSON.stringify(unfinishAppleOrder1));


        _iap.requestProduct(_productIds, function(e) {  
            // 获取订单信息成功回调方法  
            console.log('requestProduct success');
            console.log(e);
            _productDetail = e[0];
            resolve(e);

          }, function(err) {
            // 获取订单信息失败回调方法
            closeLoading();
            console.log('requestProduct failed: ' + JSON.stringify(e));
            reject(err)
        });
    })
}


export const requestPayment = ()=>{
    return new Promise((resolve, reject) => {

    console.log('merOrderId-'+_merOrderId)

      uni.requestPayment({
        provider: 'appleiap',
        orderInfo: {
            productid: _productIds[0],
            username: 'merOrderId-'+_merOrderId, 
            manualFinishTransaction: true,
            // username: username + orderId //根据业务需求透传参数，关联用户和订单关系
        },
        success: (res) => {
            console.log('requestPayment success')
            console.log(res);
            _payResult = res;

            resolve(res);
        },
        fail: (err) => {
            console.log('requestPayment error')
            console.log(err)
          reject(err);
        }
      });
    });
}

export const checkResult = async(merOrderId:string)=>{
    const USER_DATA = userData();
    const params = {
        userId:USER_DATA.id,
        receipt:_payResult.transactionReceipt,
        isOnline:0,
        merOrderId,
        orderId:_payResult.transactionIdentifier
    }

    console.log('checkResult params')
    console.log(params)


    const res = await checkApplePayResult(params).catch();
    const {flag,message,data} = res;

    console.log('checkApplePayResult')
    console.log('checkApplePayResult')
    console.log('checkApplePayResult')
    console.log(res);

    if(flag===4){
        finishOrder(_payResult);
        return Promise.resolve(true);
    }

    if(flag!==1){
        await wait(2000);
        return await checkResult(merOrderId);
    }
    const { payStatus } = data;
    if(payStatus!==1){
        await wait(2000);
        return await checkResult(merOrderId);
    }


    finishOrder(_payResult);
    return Promise.resolve(true);


}

export const applePay = async ({appleProductId,totalAmt,productId}:any)=>{
    if(!totalAmt||!productId||!appleProductId){
        uni.showToast({
            icon: "none",
            title: '支付参数有误，请检查',
            duration: 3000,
        });
        return;
    }
    _init({appleProductId,totalAmt,productId});
    await getProvider();
    await requestProduct();
    await AdvanceOrder();
    await requestPayment();
    return await checkResult(_merOrderId);
}


export const finishOrder = async(transaction)=>{
    return new Promise((resolve, reject)=>{
        _iap.finishTransaction(transaction, (res)=>{
            let unfinishAppleOrder1 = uni.getStorageSync("unfinishAppleOrder1");
            if(unfinishAppleOrder1){
                unfinishAppleOrder1 = JSON.parse(unfinishAppleOrder1);
            }

            if(unfinishAppleOrder1.length){
                let _index = unfinishAppleOrder1.findIndex(item=>item===transaction.payment.productid);
                if(_index!==-1){
                    unfinishAppleOrder1.splice(_index, 1);
                }

                uni.setStorageSync("unfinishAppleOrder1",JSON.stringify(unfinishAppleOrder1));

            }


        }, (err)=>{
            console.log('check finishTransaction err')
            console.log(err)
            reject(err)
        });
    })


}


export const getHistoryOrder = async()=>{
    return new Promise((resolve, reject)=>{
        _iap.restoreCompletedTransactions({
            manualFinishTransaction: true,
        }, (res)=>{
            console.log('getHistoryOrder1111')
            console.log('getHistoryOrder1111')
            console.log('getHistoryOrder1111')
            console.log(res);
            console.log('length')
            console.log(res.length);
            resolve(res);
        }, e => { //第一个参数必传，否则会导致app闪退！  
            reject(e);
        }); 
    })
}


const IapTransactionState = {
    purchasing: "0", // A transaction that is being processed by the App Store.
    purchased: "1", // A successfully processed transaction.
    failed: "2", // A failed transaction.
    restored: "3", // A transaction that restores content previously purchased by the user.
    deferred: "4" // A transaction that is in the queue, but its final status is pending external action such as Ask to Buy.
};

export const checkOldOrder = async()=>{
    if(uni.getSystemInfoSync().platform!=='ios'){
        return Promise.resolve(true);
    }

    let unfinishAppleOrder1 = uni.getStorageSync("unfinishAppleOrder1");

    if(!unfinishAppleOrder1){
        return Promise.resolve(true);
    }else{
        unfinishAppleOrder1 = JSON.parse(unfinishAppleOrder1)
    }

    if(!unfinishAppleOrder1.length){
        return Promise.resolve(true);
    }

    const SYSTEM_CONFIG:any = systemConfig()
    if(!SYSTEM_CONFIG.userVip.length){
        return Promise.resolve(true);
    }


    await getProvider();
    const historyOrder = await getHistoryOrder();
    for(let i=0;i<historyOrder.length;i++){
        const transaction = historyOrder[i];
        const { transactionState } = transaction;
        // console.log('transaction')
        // console.log(transaction)
        // console.log('transactionState')
        // console.log(transactionState);
        if(transactionState==='3'){
            finishOrder(transaction)

        }
        if(transactionState==='2'){
            finishOrder(transaction)
        }

        if(transactionState==='1'){
            uni.showLoading({
                mask: true,
				title: '检测到有未完成的订单，请耐心等待'
            });



            const { productid } = transaction.payment;

            _advanceOrderProId = null;
            _totalAmount = null;
            SYSTEM_CONFIG.userVip.forEach((item:any)=>{
                const p = item?.slimValue?.split("|")[2];
                const amount = item?.slimValue?.split("|")[0];

                if(productid===p){
                    _advanceOrderProId = item.id
                    _totalAmount = amount
                    _payResult = transaction
                }
            })



            if(!_advanceOrderProId||!_totalAmount){
                break;
            }
            await AdvanceOrder()
            await checkResult(_merOrderId);
        }

    }

    uni.hideLoading();
    return Promise.resolve(true);



}


export const restore = async ()=>{

    console.log('restore')
    console.log('restore')
    console.log('restore')

    let unfinishAppleOrder1 = uni.getStorageSync("unfinishAppleOrder1");

    console.log('unfinishAppleOrder1')
    console.log('unfinishAppleOrder1')
    console.log('unfinishAppleOrder1')
    console.log(unfinishAppleOrder1)

    if(!unfinishAppleOrder1){
        return;
    }

    if(unfinishAppleOrder1){
        unfinishAppleOrder1 = JSON.parse(unfinishAppleOrder1);
    }

    if(!unfinishAppleOrder1.length){
        return;
    }


    const SYSTEM_CONFIG:any = systemConfig()
    if(!SYSTEM_CONFIG.userVip.length){
        return;
    }


    await getProvider();
    const historyOrder = await getHistoryOrder();

    if(!historyOrder){
        return Promise.reject(false)
    }

    if(!historyOrder.length){
        return Promise.resolve(true)
    }


    



    for(let i=0;i<historyOrder.length;i++){
        const transaction = historyOrder[i];
        const { transactionState } = transaction;
        // console.log('transaction')
        // console.log(transaction)
        // console.log('transactionState')
        // console.log(transactionState);
        if(transactionState==='3'){
            finishOrder(transaction)

        }
        if(transactionState==='2'){
            finishOrder(transaction)

        }

        if(transactionState==='1'){

            //finishOrder(transaction);

            const { productid } = transaction.payment;

            _advanceOrderProId = null;
            _totalAmount = null;
            SYSTEM_CONFIG.userVip.forEach((item:any)=>{
                const p = item?.slimValue?.split("|")[2];
                const amount = item?.slimValue?.split("|")[0];

                if(productid===p){
                    _advanceOrderProId = item.id
                    _totalAmount = amount
                    _payResult = transaction
                }
            })



            if(!_advanceOrderProId||!_totalAmount){
                break;
            }
            await AdvanceOrder()
            await checkResult(_merOrderId);
        }

    }



}